﻿#include <WS2tcpip.h>
#include <windows.h>
#include <iostream>
#include <thread>
#pragma comment(lib, "ws2_32.lib")
using namespace std;


int main()
{
    // 初始化WinSock
    WSADATA ws;
    WSAStartup(MAKEWORD(2,2), &ws);
    
    // 创建socket套接字
    int server = socket(AF_INET, SOCK_STREAM, 0);
    if (server == -1) {
        cout << "创建套接字失败" << endl;
        return -1;
    }

    // 设置地址和端口
    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.S_un.S_addr = INADDR_ANY;
    addr.sin_port = htons(8000);

    // bind绑定端口
    int bindRet = bind(server, (sockaddr*)&addr, sizeof(addr));
    if(bindRet == -1){
        cout << "绑定端口失败" << endl;
        closesocket(server);
        return -1;
    }

    // listen监听端口
    int lisRet = listen(server, 100);
    if (lisRet == -1) {
        cout << "监听失败：" << errno << endl;
        closesocket(server);
        return -1;
    }
    cout << "服务已经开启，正在监听端口..." << endl;
    int addr_size = 666;
    while (true)
    {
        // 接受客户端连接
        int client = accept(server, (sockaddr*)&addr, &addr_size);
        if (client == -1) {
            cout << "接收客户端异常：" << errno << endl;
            break;
        }
        thread t([](sockaddr_in addr, int client) {
            char buf[100];
            cout << "客户端：" << inet_ntop(AF_INET, (void*)&addr.sin_addr, buf, sizeof(buf)) << ":" << addr.sin_port << endl;
            // 接收客户端的数据
            int reRet = recv(client, buf, sizeof(buf), 0);
            if (reRet == -1) {
                cout << "接收失败:" << errno << endl;
            }
            else {
                cout << "收到:" << buf << endl;
            }

            // 发送数据给客户端
            strcpy_s(buf, 100, "喂，你好！我是服务端！");

            int seRet = send(client, buf, sizeof(buf), 0);
            if (seRet == -1) {
                cout << "发送失败:" << errno << endl;
            }
            else {
                cout << "发送成功!" << endl;
            }
            closesocket(client);
        }, addr, client);
        t.detach();
    }
    closesocket(server);
    cout << "服务退出" << endl;
    system("pause");

    return 0;
}